﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using JY.Label.PrintHelper.CommuicationModel;
using Microsoft.Win32.SafeHandles;

namespace JY.Label.PrintHelper
{

    /// <summary>
    /// 标签打印帮助类
    /// </summary>
    public static class LabelPrintHelper
    {
        #region # 字段

        private static PrinterCommunicationType _printerCommunicationType;
        private static ICommuicationModel _commuicationModel;
        private static object _syncRoot = new object();//线程锁
        private static int _pausePrintCount = 100;//暂停的打印数量
        private static int _pauseTime = 200;//暂停时长200毫秒
        private static int _printWaitTime = 30;//打印一个暂停30毫秒

        #endregion

        #region # 初始化配置——void  InitPrinter(PrinterCommunicationType printerCommunicationType, ICommuicationModel commuicationModel)
        /// <summary>
        /// 初始化配置
        /// </summary>
        /// <param name="printerCommunicationType">打印机通讯方式</param>
        /// <param name="commuicationModel">通讯模型</param>
        public static void InitPrinter(PrinterCommunicationType printerCommunicationType, ICommuicationModel commuicationModel)
        {
            _printerCommunicationType = printerCommunicationType;
            _commuicationModel = commuicationModel;
        }
        #endregion

        #region # 多个标签打印配置
        /// <summary>
        /// 多个标签打印配置
        /// </summary>
        /// <param name="pausePrintCount">暂停的打印数量</param>
        /// <param name="pauseTime">暂停时长200毫秒</param>
        /// <param name="printWaitTime">打印一个暂停30毫秒</param>
        public static void MultiplePrintConfig(int pausePrintCount, int pauseTime, int printWaitTime)
        {
            _pausePrintCount = pausePrintCount;
            _pauseTime = pauseTime;
            _printWaitTime = printWaitTime;
        }
        #endregion

        #region # 打印标签——void PrintLabel(string labelCommand)
        /// <summary>
        /// 打印标签
        /// </summary>
        /// <param name="labelCommand">标签命令</param>
        public static void PrintLabel(string labelCommand)
        {
            if (_commuicationModel == null)
            {
                throw new Exception("尚未初始化打印机通讯配置！不能操作！");
            }

            lock (_syncRoot)
            {
                try
                {
                    switch (_printerCommunicationType)
                    {
                        case PrinterCommunicationType.Com:
                            PrintLabelByCom(labelCommand, _commuicationModel as ComModel);
                            break;
                        case PrinterCommunicationType.Tcp:
                            PrintLabelByTcp(labelCommand, _commuicationModel as TcpModel);
                            break;
                        case PrinterCommunicationType.Lpt:
                            PrintLabelByLpt(labelCommand, _commuicationModel as LptModel);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"打印标签失败！原因：{ex.Message}", ex);
                }
            }
        }
        #endregion

        #region # 通过串口打印标签——void PrintLabelByCom(string labelCommand, ComModel comModel)
        /// <summary>
        /// 通过串口打印标签
        /// </summary>
        /// <param name="labelCommand">打印命令</param>
        /// <param name="comModel">串口模型</param>
        /// <returns></returns>
        public static void PrintLabelByCom(string labelCommand, ComModel comModel)
        {
            try
            {
                byte[] printDatas = comModel.PrinterEncoding.GetBytes(labelCommand);
                using (SerialPort serialPort = new SerialPort(comModel.PortName, comModel.BaudRate, comModel.Parity, comModel.DataBits, comModel.StopBits))
                {
                    serialPort.Open();
                    serialPort.Write(printDatas, 0, printDatas.Length);
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"串口打印标签失败！原因：{ex.Message}", ex);
            }
        }
        #endregion

        #region # 通过Tcp打印标签—— void PrintLabelByTcp(string labelCommand, TcpModel tcpModel)
        /// <summary>
        /// 通过Tcp打印标签
        /// </summary>
        /// <param name="labelCommand">打印命令</param>
        /// <param name="tcpModel">TCP模型</param>
        /// <returns></returns>
        public static void PrintLabelByTcp(string labelCommand, TcpModel tcpModel)
        {
            try
            {
                byte[] printDatas = tcpModel.PrinterEncoding.GetBytes(labelCommand);
                using (TcpClient tcpClient = new TcpClient())
                {
                    tcpClient.Connect(tcpModel.IpAddress, tcpModel.Port);
                    using (NetworkStream networkStream = tcpClient.GetStream())
                    {
                        networkStream.Write(printDatas, 0, printDatas.Length);
                        networkStream.Flush();
                        networkStream.Close();
                        tcpClient.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Tcp打印标签失败，请检查打印机或网络设置！原因：{ex.Message}", ex);
            }
        }
        #endregion

        #region # 通过Lpt端口打印标签——void PrintLabelByLpt(string labelCommand, LptModel lptModel)
        /// <summary>
        /// 通过Lpt端口打印标签
        /// </summary>
        /// <param name="labelCommand">打印命令</param>
        /// <param name="lptModel">Lpt模型</param>
        public static void PrintLabelByLpt(string labelCommand, LptModel lptModel)
        {
            try
            {
                using (SafeFileHandle safeFileHandle = LptPrintHelper.CreateFile(lptModel.LptPortName))
                {
                    if (!safeFileHandle.IsInvalid)
                    {
                        using (FileStream fileStream = new FileStream(safeFileHandle, FileAccess.ReadWrite))
                        {
                            using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default))
                            {
                                byte[] printDatas = lptModel.PrinterEncoding.GetBytes(labelCommand);
                                streamWriter.Write(printDatas);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception($"Lpt端口[{lptModel.LptPortName}]连接失败！");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"打印失败，请检查打印机或Lpt端口连接！原因：{ex.Message}", ex);
            }
        }
        #endregion

        #region # 通过Usb打印标签——void PrintLabelByUsb(string labelCommand, UsbModel usbModel)
        /// <summary>
        /// 通过Usb打印标签
        /// </summary>
        /// <param name="labelCommand">打印命令</param>
        /// <param name="usbModel">Usb模型</param>
        public static void PrintLabelByUsb(string labelCommand, UsbModel usbModel)
        {
            try
            {
                UsbPrintHelper.SendStringToPrinter(usbModel.PrinterName, labelCommand, usbModel.PrinterEncoding);
            }
            catch (Exception ex)
            {
                throw new Exception($"打印失败，请检查打印机或Lpt端口连接！原因：{ex.Message}", ex);
            }
        }
        #endregion

        //多标签打印
        #region # 打印多标签——void PrintLabels(List<string> labelCommands)
        /// <summary>
        /// 打印多标签
        /// </summary>
        /// <param name="labelCommands">标签命令列表</param>
        public static void PrintLabels(List<string> labelCommands)
        {
            if (_commuicationModel == null)
            {
                throw new Exception("尚未初始化打印机通讯配置！不能操作！");
            }

            lock (_syncRoot)
            {
                try
                {
                    switch (_printerCommunicationType)
                    {
                        case PrinterCommunicationType.Com:
                            PrintLabelsByCom(labelCommands, _commuicationModel as ComModel);
                            break;
                        case PrinterCommunicationType.Tcp:
                            PrintLabelsByTcp(labelCommands, _commuicationModel as TcpModel);
                            break;
                        case PrinterCommunicationType.Lpt:
                            PrintLabelsByLpt(labelCommands, _commuicationModel as LptModel);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
            }
        }
        #endregion

        #region # 通过串口打印多标签——void PrintLabelsByCom(List<string> labelCommands, ComModel comModel)
        /// <summary>
        /// 通过串口打印多标签
        /// </summary>
        /// <param name="labelCommands">标签命令列表</param>
        /// <param name="comModel">串口模型</param>
        /// <returns></returns>
        public static void PrintLabelsByCom(List<string> labelCommands, ComModel comModel)
        {
            try
            {
                int printCount = 0;
                using (SerialPort serialPort = new SerialPort(comModel.PortName, comModel.BaudRate, comModel.Parity, comModel.DataBits, comModel.StopBits))
                {
                    serialPort.Open();
                    foreach (var labelCommand in labelCommands)
                    {
                        byte[] printDatas = comModel.PrinterEncoding.GetBytes(labelCommand);
                        serialPort.Write(printDatas, 0, printDatas.Length);
                        Thread.Sleep(printCount <= _pausePrintCount ? _printWaitTime : _pauseTime);
                        printCount++;
                    }
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
        #endregion

        #region # 通过Tcp打印多标签—— void PrintLabelsByTcp(List<string> labelCommands, TcpModel tcpModel)
        /// <summary>
        /// 通过Tcp打印多标签
        /// </summary>
        /// <param name="labelCommands">标签命令列表</param>
        /// <param name="tcpModel">TCP模型</param>
        /// <returns></returns>
        public static void PrintLabelsByTcp(List<string> labelCommands, TcpModel tcpModel)
        {
            try
            {
                int printCount = 0;
                using (TcpClient tcpClient = new TcpClient())
                {
                    tcpClient.Connect(tcpModel.IpAddress, tcpModel.Port);
                    using (NetworkStream networkStream = tcpClient.GetStream())
                    {
                        foreach (var labelCommand in labelCommands)
                        {
                            byte[] printDatas = tcpModel.PrinterEncoding.GetBytes(labelCommand);
                            networkStream.Write(printDatas, 0, printDatas.Length);
                            Thread.Sleep(printCount <= _pausePrintCount ? _printWaitTime : _pauseTime);
                            printCount++;
                        }
                        
                        networkStream.Flush();
                        networkStream.Close();
                        tcpClient.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("打印失败，请检查打印机或网络设置。", ex);
            }
        }
        #endregion

        #region # 通过Lpt打印多标签——void PrintLabelsByLpt(string labelCommand, LptModel lptModel)
        /// <summary>
        /// 通过Lpt打印多标签
        /// </summary>
        /// <param name="labelCommands">打印命令列表</param>
        /// <param name="lptModel">Lpt模型</param>
        public static void PrintLabelsByLpt(List<string> labelCommands, LptModel lptModel)
        {
            try
            {
                using (SafeFileHandle safeFileHandle = LptPrintHelper.CreateFile(lptModel.LptPortName))
                {
                    if (!safeFileHandle.IsInvalid)
                    {
                        using (FileStream fileStream = new FileStream(safeFileHandle, FileAccess.ReadWrite))
                        {
                            using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default))
                            {
                                foreach (var labelCommand in labelCommands)
                                {
                                    byte[] printDatas = lptModel.PrinterEncoding.GetBytes(labelCommand);
                                    streamWriter.Write(printDatas);
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception($"Lpt端口[{lptModel.LptPortName}]连接失败！");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"打印失败，请检查打印机或Lpt端口连接！原因：{ex.Message}", ex);
            }
        }
        #endregion

        #region # 通过USB打印多标签——void PrintLabelsByUsb(List<string> labelCommands, UsbModel usbModel)
        /// <summary>
        /// 通过USB打印多标签
        /// </summary>
        /// <param name="labelCommands">打印命令列表</param>
        /// <param name="usbModel">USB模型</param>
        public static void PrintLabelsByUsb(List<string> labelCommands, UsbModel usbModel)
        {
            try
            {
                foreach (var labelCommand in labelCommands)
                {
                    UsbPrintHelper.SendStringToPrinter(usbModel.PrinterName, labelCommand, usbModel.PrinterEncoding);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"打印失败，请检查打印机或Usb连接！原因：{ex.Message}", ex);
            }
        }
        #endregion
    }
}
